import * as fs from 'fs';
import * as path from 'path';
import { swaggerSpec } from '../src/config/swagger';

// 由于js-yaml可能未安装，我们使用内置的方法
const yaml = {
  dump: (obj: any, options?: any) => {
    // 简单的YAML转换，如果需要更复杂的功能，请安装js-yaml
    return JSON.stringify(obj, null, 2).replace(/"/g, '').replace(/:/g, ': ');
  }
};

/**
 * 导出OpenAPI规范到文件
 */
class OpenAPIExporter {
  private outputDir: string;

  constructor(outputDir: string = 'docs/api') {
    this.outputDir = outputDir;
    this.ensureOutputDirectory();
  }

  /**
   * 确保输出目录存在
   */
  private ensureOutputDirectory(): void {
    if (!fs.existsSync(this.outputDir)) {
      fs.mkdirSync(this.outputDir, { recursive: true });
    }
  }

  /**
   * 导出JSON格式的OpenAPI规范
   */
  public exportJSON(): void {
    const outputPath = path.join(this.outputDir, 'openapi.json');
    const jsonContent = JSON.stringify(swaggerSpec, null, 2);
    
    fs.writeFileSync(outputPath, jsonContent, 'utf8');
    console.log(`✅ OpenAPI规范已导出到: ${outputPath}`);
  }

  /**
   * 导出YAML格式的OpenAPI规范
   */
  public exportYAML(): void {
    const outputPath = path.join(this.outputDir, 'openapi.yaml');
    const yamlContent = yaml.dump(swaggerSpec, {
      indent: 2,
      lineWidth: -1,
      noRefs: true,
      skipInvalid: true
    });
    
    fs.writeFileSync(outputPath, yamlContent, 'utf8');
    console.log(`✅ OpenAPI规范已导出到: ${outputPath}`);
  }

  /**
   * 导出Postman集合格式
   */
  public exportPostman(): void {
    const outputPath = path.join(this.outputDir, 'postman-collection.json');
    const spec = swaggerSpec as any;
    
    // 基本的Postman集合结构
    const postmanCollection = {
      info: {
        name: spec.info?.title || 'API Collection',
        description: spec.info?.description || '',
        version: spec.info?.version || '1.0.0',
        schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
      },
      item: [],
      variable: [
        {
          key: "baseUrl",
          value: spec.servers?.[0]?.url || "http://localhost:3379",
          type: "string"
        }
      ]
    };

    // 这里可以进一步扩展，将OpenAPI路径转换为Postman请求
    // 为了简化，我们先创建基本结构
    
    const postmanContent = JSON.stringify(postmanCollection, null, 2);
    fs.writeFileSync(outputPath, postmanContent, 'utf8');
    console.log(`✅ Postman集合已导出到: ${outputPath}`);
  }

  /**
   * 生成API文档摘要
   */
  public generateSummary(): void {
    const outputPath = path.join(this.outputDir, 'api-summary.md');
    const spec = swaggerSpec as any;
    
    let markdown = `# ${spec.info?.title || 'API Documentation'}\n\n`;
    markdown += `${spec.info?.description || ''}\n\n`;
    markdown += `**版本:** ${spec.info?.version || 'N/A'}\n\n`;
    
    if (spec.servers && Array.isArray(spec.servers)) {
      markdown += `## 服务器\n\n`;
      spec.servers.forEach((server: any) => {
        markdown += `- ${server.description || 'Server'}: \`${server.url || ''}\`\n`;
      });
      markdown += '\n';
    }

    if (spec.tags && Array.isArray(spec.tags)) {
      markdown += `## API分组\n\n`;
      spec.tags.forEach((tag: any) => {
        markdown += `- **${tag.name || 'Unnamed'}**: ${tag.description || ''}\n`;
      });
      markdown += '\n';
    }

    markdown += `## 文档格式\n\n`;
    markdown += `- [JSON格式](./openapi.json)\n`;
    markdown += `- [YAML格式](./openapi.yaml)\n`;
    markdown += `- [Postman集合](./postman-collection.json)\n\n`;

    markdown += `## 在线文档\n\n`;
    markdown += `访问 [http://localhost:3379/api-docs](http://localhost:3379/api-docs) 查看交互式API文档。\n\n`;

    markdown += `## 生成时间\n\n`;
    markdown += `${new Date().toLocaleString('zh-CN')}\n`;

    fs.writeFileSync(outputPath, markdown, 'utf8');
    console.log(`✅ API摘要已生成到: ${outputPath}`);
  }

  /**
   * 导出所有格式
   */
  public exportAll(): void {
    console.log('🚀 开始导出OpenAPI规范...\n');
    
    this.exportJSON();
    this.exportYAML();
    this.exportPostman();
    this.generateSummary();
    
    console.log('\n✨ 所有格式导出完成！');
    console.log(`📁 输出目录: ${path.resolve(this.outputDir)}`);
  }
}

// 脚本入口
if (require.main === module) {
  const exporter = new OpenAPIExporter();
  
  const args = process.argv.slice(2);
  
  if (args.length === 0 || args.includes('--all')) {
    exporter.exportAll();
  } else {
    if (args.includes('--json')) {
      exporter.exportJSON();
    }
    if (args.includes('--yaml')) {
      exporter.exportYAML();
    }
    if (args.includes('--postman')) {
      exporter.exportPostman();
    }
    if (args.includes('--summary')) {
      exporter.generateSummary();
    }
  }
}

export { OpenAPIExporter }; 